package com.thememaker.lockstyle;

import com.jfoenix.controls.JFXButton;
import com.thememake.ui.CtsFileChooser;
import com.thememake.ui.Toast;
import com.thememake.util.FileUtils;
import com.thememaker.util.SVGLoadUtils;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

import static com.thememaker.lockstyle.LockstyleMainController.buttonColor;

/**
 * @author yiyi.zheng 2018/9/18
 */
public class LockstyleLeftFileTree {
    private Stage stage;
    private VBox leftFileAnchorPane;
    private Path lockscreenPath;
    private LockstyleShowUtils lockstyleShowUtils;
    private boolean isDoubleClick = false;

    public LockstyleLeftFileTree(Stage stage, VBox leftFileAnchorPane, Path lockscreenPath, LockstyleShowUtils lockstyleShowUtils) {
        this.stage = stage;
        this.leftFileAnchorPane = leftFileAnchorPane;
        this.lockscreenPath = lockscreenPath;
        this.lockstyleShowUtils = lockstyleShowUtils;
    }

    private void clearView() {
        if (leftFileAnchorPane.getChildren() != null && leftFileAnchorPane.getChildren().size() > 0) {
            leftFileAnchorPane.getChildren().remove(0, leftFileAnchorPane.getChildren().size());
        }
    }

    public TreeView addFileTree() {
        clearView();
        LockTreeItem<File> lockTreeItem = new LockTreeItem<>();
        lockTreeItem.setTag(lockscreenPath.toFile());
        lockTreeItem.setName(lockscreenPath.toFile().getName());
        lockTreeItem.setValue(lockscreenPath.toFile());
        getFilePath(lockscreenPath.toFile(), lockTreeItem);
        TreeView treeView = new TreeView<>(lockTreeItem);
        treeView.setPrefWidth(250);
        treeView.setPrefHeight(1080);
        treeView.getSelectionModel().select(0);
        lockTreeItem.setExpanded(true);
        ContextMenu contextMenu = new ContextMenu();
        MenuItem register1 = new MenuItem("新建文件夹");
        MenuItem register2 = new MenuItem("添加文件");
        MenuItem register3 = new MenuItem("打开所在路径");
        MenuItem register4 = new MenuItem("删除");
        treeView.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
            LockTreeItem<File> selectedItem = (LockTreeItem<File>) treeView.getSelectionModel().getSelectedItem();
            switch (event.getButton()) {
                case SECONDARY:
                    if (contextMenu.getItems() != null) {
                        contextMenu.getItems().remove(0, contextMenu.getItems().size());
                    }
                    if (selectedItem.getTag().isDirectory()) {
                        contextMenu.getItems().addAll(register1, register2, register3, register4);
                    } else {
                        contextMenu.getItems().addAll(register3, register4);
                    }
                    treeView.setContextMenu(contextMenu);
                    break;
                case PRIMARY:
                    if (isDoubleClick) {
                        if (!selectedItem.getTag().isDirectory()) {
                            try {
                                Desktop.getDesktop().open(selectedItem.getTag());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        isDoubleClick = true;
                        new Thread(() -> {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                isDoubleClick = false;
                            }
                        }).start();
                    }
                    break;
                default:
                    break;
            }
        });
        register1.setOnAction(event1 -> {
            LockTreeItem<File> item = (LockTreeItem<File>) treeView.getSelectionModel().getSelectedItem();
            showDialog(item.getTag().getPath() + File.separator, lockTreeItem);
        });
        register2.setOnAction(event1 -> {
            LockTreeItem<File> item = (LockTreeItem<File>) treeView.getSelectionModel().getSelectedItem();
            File addFile = CtsFileChooser.getInstance().showOpenDialog(stage, "添加文件", new FileChooser.ExtensionFilter("PNG,JPEG File", "*.png", "*.jpg"));
            FileUtils.copyFile(addFile.getPath(), item.getTag() + File.separator + addFile.getName(), true);
            Toast.makeText(stage, "添加成功", 2000);
            lockstyleShowUtils.showLockscreen();
        });
        register3.setOnAction(event -> {
            LockTreeItem<File> item = (LockTreeItem<File>) treeView.getSelectionModel().getSelectedItem();
            try {
                Desktop.getDesktop().open(item.getTag().getParentFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        register4.setOnAction(event1 -> {
            LockTreeItem<File> item = (LockTreeItem<File>) treeView.getSelectionModel().getSelectedItem();
            FileUtils.deleteDir(item.getTag());
            Toast.makeText(stage, "删除成功", 2000);
            lockstyleShowUtils.showLockscreen();
        });
        treeView.setCellFactory(new Callback<TreeView<File>, TreeCell<File>>() {
            @Override
            public TreeCell<File> call(TreeView<File> param) {
                TreeCell<File> treeCell = new TreeCell<File>() {
                    @Override
                    protected void updateItem(File item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setText(null);
                            setGraphic(null);
                        } else {
                            if (item.isDirectory()) {
                                setGraphic(SVGLoadUtils.getInstance().getFolderSVG(15, buttonColor));
                            } else {
                                if (item.getName().endsWith(".png") || item.getName().endsWith(".jpg")) {
                                    setGraphic(SVGLoadUtils.getInstance().getImageSVG(15, buttonColor));
                                } else {
                                    setGraphic(SVGLoadUtils.getInstance().getFileSVG(15, buttonColor));
                                }
                            }
                            setText(item.getName());
                            setId("diy-fontColor");
                        }
                    }
                };
                return treeCell;
            }
        });
        return treeView;
    }

    private void getFilePath(File file, LockTreeItem<File> lockTreeItem) {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            LockTreeItem<File> item = new LockTreeItem<>();
            item.setExpanded(false);
            item.setTag(files[i]);
            item.setName(files[i].getName());
            item.setValue(files[i]);
            if (files[i].isDirectory()) {
                lockTreeItem.getChildren().addAll(item);
                getFilePath(files[i], item);
            } else {
                lockTreeItem.getChildren().addAll(item);
            }
        }
    }

    private void showDialog(String path, LockTreeItem<File> lockTreeItem) {
        StackPane stackPane = new StackPane();
        stackPane.setAlignment(Pos.CENTER);
        stackPane.getStylesheets().add("style/lockstylemain.css");
        Stage secondWindow = new Stage();
        Scene scene = new Scene(stackPane, 300, 100);
        secondWindow.setTitle("新建");
        secondWindow.setScene(scene);
        secondWindow.show();
        Label label = new Label("文件名：");
        label.setId("diy-fontColor");
        TextField textField = new TextField();
        textField.setPrefWidth(100);
        textField.setId("diy-textfield");
        HBox.setMargin(textField, new Insets(0, 10, 0, 10));
        JFXButton button = new JFXButton("确定");
        button.setPrefWidth(100);
        button.setPrefHeight(20);
        button.setStyle("-fx-text-fill:WHITE;-fx-background-color:#5264AE;-fx-font-size:14px;");
        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER);
        hBox.setPrefWidth(300);
        hBox.setPrefHeight(100);
        hBox.getChildren().addAll(label, textField, button);
        stackPane.getChildren().addAll(hBox);
        button.setOnAction(event -> {
        });
    }
}
